<template>
  <div class="app-container">
    <h2 style="text-align: center;">发布新课程</h2>
    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="提交审核"></el-step>
    </el-steps>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>
      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select
          v-model="courseInfo.teacherId"
          placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"/>
        </el-select>
      </el-form-item>
      <!-- 所属分类：级联下拉列表 -->
      <!-- 一级分类 -->
      <el-form-item label="课程类别">
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="请选择" @change="subjectLevelOneChanged">
          <el-option
            v-for="subject in oneLevelSubjectList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>

        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId" placeholder="请选择">
          <el-option
            v-for="subject in twoLevelSubjectList"
            :key="subject.value"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>
      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/oss/upload?folderName=career/img/'+subject.parentId"
          class="avatar-uploader">
          <img :src="courseInfo.cover">
        </el-upload>
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/>
        元
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">保存并下一步</el-button>
        <el-button :disabled="false" type="primary" @click="resetData">重置</el-button>
        <el-button :disabled="false" type="primary" @click="saveAndGoToCourseList">保存并返回课程列表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
    import course from '@/api/course'
    import teacher from '@/api/teacher'
    import subject from '@/api/subject'
    import Tinymce from '@/components/Tinymce'

    const defaultForm = {
        id: '',
        title: '',
        subjectId: '',
        teacherId: '',
        subjectParentId: '',
        lessonNum: 0,
        description: '',
        cover: '/static/01.jpg',
        price: 0
    }
    export default {
        components: { Tinymce },
        name: "info",
        data() {
            return {
                saveBtnDisabled: false,
                courseInfo: defaultForm,
                teacherList: [],
                BASE_API: process.env.BASE_API, // 接口API地址
                oneLevelSubjectList: [],//一级分类列表
                twoLevelSubjectList: [] //二级分类列表
            };
        },

        created() {
          this.init()
        },

        watch: {
            $route(to,from){
                this.init()
            }
        },

        methods: {
            resetData() {
                this.init()
                this.saveBtnDisabled = false
            },
            init() {
                this.getTeacherList()
                // this.initSubjectList()
                //回显
                if (this.$route.params && this.$route.params.id) {
                    course.getCourseInfoById(this.$route.params.id)
                        .then(response => {
                            if (response.data.success) {
                                this.initSubjectList()
                                // this.subjectLevelOneChanged(this.courseInfo.subjectParentId)
                                this.courseInfo = response.data.data.courseInfo
                            }
                        })
                        .catch(response => {

                        })

                }else {
                    this.courseInfo = {...defaultForm}
                    this.initSubjectList()
                    this.twoLevelSubjectList = []
                }

            },
            next() {

                if (this.courseInfo.title === '') {
                    this.$message({
                        type: 'error',
                        message: '课程标题不能为空'
                    })
                    return;
                }
                if (this.courseInfo.teacherId === '') {
                    this.$message({
                        type: 'error',
                        message: '课程讲师不能为空'
                    })
                    return;
                }
                if (this.courseInfo.lessonNum === 0) {
                    this.$message({
                        type: 'error',
                        message: '课程总课时不能为0'
                    })
                    return;
                }
                if (this.courseInfo.subjectId === '') {
                    this.$message({
                        type: 'error',
                        message: '课程类别不能为空'
                    })
                    return;
                }
                this.saveBtnDisabled = true
                course.saveCourseInfo(this.courseInfo)
                .then(response => {
                    if (response.data.success) {
                        this.courseInfo.id = response.data.data.courseId
                        //路由跳转，到编写大纲页面
                        this.$message({
                            type: 'success',
                            message: `${response.data.message}`
                        })
                        this.$router.push({path: '/edu/course/chapter/'+ this.courseInfo.id})
                    }else {
                        this.$message({
                            type: 'error',
                            message: `${response.data.message}`
                        })
                    }
                })
                .catch(response => {
                    this.$message({
                        type: 'error',
                        message: response.message
                    })
                })

            },
            getTeacherList() {
                teacher.getTeacherList()
                    .then(response => {
                        if (response.data.success) {
                            this.teacherList = response.data.data.items
                        }
                    })
                    .catch(response => {

                    })
            },

            initSubjectList() {
                subject.getAllSubjectList()
                    .then(response => {
                        if (response.data.success) {
                            this.oneLevelSubjectList = response.data.data.items
                            if (this.courseInfo.subjectParentId !== '') {
                                var sid = this.courseInfo.subjectId;
                                this.subjectLevelOneChanged(this.courseInfo.subjectParentId)
                                this.courseInfo.subjectId = sid
                            }

                        }
                    })
                    .catch(response => {

                    })
            },

            subjectLevelOneChanged(value) {
                for (let i = 0; i < this.oneLevelSubjectList.length; i++) {
                    if(this.oneLevelSubjectList[i].id === value) {
                        this.twoLevelSubjectList = this.oneLevelSubjectList[i].children
                        this.courseInfo.subjectId = ''
                    }
                }
            },

            handleAvatarSuccess(res, file) {
                console.log(res)// 上传响应
                console.log(URL.createObjectURL(file.raw))// base64编码
                this.courseInfo.cover = res.data.imgUrl
            },

            beforeAvatarUpload(file) {
                const isJPG = (file.type === 'image/jpeg') | (file.type === 'image/png') | (file.type === 'image/gif')
                const isLt2M = file.size / 1024 / 1024 < 2
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!')
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!')
                }
                return isJPG && isLt2M
            },
            /*保存并返回课程列表*/
            saveAndGoToCourseList() {
                if (this.courseInfo.title === '') {
                    this.$message({
                        type: 'error',
                        message: '课程标题不能为空'
                    })
                    return;
                }
                if (this.courseInfo.teacherId === '') {
                    this.$message({
                        type: 'error',
                        message: '课程讲师不能为空'
                    })
                    return;
                }
                if (this.courseInfo.lessonNum === 0) {
                    this.$message({
                        type: 'error',
                        message: '课程总课时不能为0'
                    })
                    return;
                }
                if (this.courseInfo.subjectId === '') {
                    this.$message({
                        type: 'error',
                        message: '课程类别不能为空'
                    })
                    return;
                }
                this.saveBtnDisabled = true
                course.saveCourseInfo(this.courseInfo)
                    .then(response => {
                        this.$router.push({path: '/edu/course/list/'})
                        if (this.courseInfo.id === '') {
                            this.$message({
                                type: 'success',
                                message: '保存成功'
                            })
                        }else{
                            this.$message({
                                type: 'success',
                                message: '修改成功'
                            })
                        }
                    })
            }
        }
    }
</script>

<style scoped>
  .tinymce-container {
    line-height: 29px;
  }
</style>
